﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace LED_Editor.Model
{
    public class FrameSource : BindingSourceEx//Collection<FrameStruct>
    {
        private Track _Owner;

        public void SetTrack(Track owner)
        {
            _Owner = owner;
        }


        public FrameSource()
            : base()
        {
            this.DataSource = typeof(Frame);
            //this.AddingNew += new AddingNewEventHandler(FrameSource_AddingNew);
            this.AllowNew = true;
        }

        //public FrameSource(Track owner): base()
        //{
        //    this.DataSource = typeof(Frame);
        //    _Owner = owner;
        //}

        public FrameSource(IContainer container)
            : base(container)
        {
            this.DataSource = typeof(Frame);
            //this.AddingNew += new AddingNewEventHandler(FrameSource_AddingNew);

        }

        protected override void OnListChanged(ListChangedEventArgs e)
        {
            base.OnListChanged(e);
            ReCalculate();
        }

        protected void ReCalculate()
        {

            int duration = 0;
            switch (base.Count)
            {
                case 0:
                    return;
                default:
                    Frame first = (Frame)base.List[0];
                    duration = first.FrameDuration;
                    first.NotifyChanges = false;
                    first.StartMarker =0;
                    first.EndMarker  = duration;
                    first.NotifyChanges = true;

                    for (int i = 0; i < base.Count - 1; i++)
                    {
                        Frame previous = (Frame)base.List[i];
                        Frame next = (Frame)base.List[i + 1];
                        int nextDuration = next.FrameDuration;
                        next.NotifyChanges = false;
                        next.StartMarker =previous.EndMarker;
                        next.EndMarker = next.StartMarker + nextDuration;
                        next.NotifyChanges = true;

                    }
                    break;
            }
        }





        void FrameSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            Frame newFrame = Frame.CreateInstance() ;
            newFrame.TrackId = _Owner.Id;
            newFrame.FrameDuration = 100;
            e.NewObject = newFrame;
        }
     
        public override object AddNew()
        {
            Frame newFrame = base.AddNew() as Frame;
           // Frame newFrame = Frame.CreateInstance();
            newFrame.TrackId = _Owner.Id;
            newFrame.FrameDuration = 100;
            return newFrame;
        }

    }
}
